import SwiftUI

struct FreeRecordingViewNew: View {
    @EnvironmentObject var sensor: SensorRecorder
    @AppStorage("userName") private var userName: String = ""
    @Environment(\.dismiss) private var dismiss
    
    // 录制状态
    @State private var isRecording: Bool = false
    @State private var isChewing: Bool = false
    @State private var elapsedTime: TimeInterval = 0
    
    // Session 数据
    @State private var session = FreeRecordingSession()
    @State private var currentSegmentStartDate: Date?
    @State private var currentSegmentStartIndex: Int = 0
    
    // UI 状态
    @State private var showNoteSheet: Bool = false
    @State private var noteText: String = ""
    @State private var showSaveButton: Bool = false
    
    // 上传状态
    @State private var isUploading: Bool = false
    @State private var uploadError: String?
    @State private var uploadSuccess: Bool = false
    
    // 定时器
    @State private var timer: Timer?
    
    var body: some View {
        ZStack {
            // 背景
            backgroundGradient
            
            VStack(spacing: 24) {
                // 顶部标题
                headerSection
                
                Spacer()
                
                // 中间状态显示
                statusSection
                
                Spacer()
                
                // 底部按钮
                controlButtons
            }
        }
        .navigationBarBackButtonHidden(isRecording)
        .onAppear {
            print("🔵 [FreeRecordingNew] 页面出现")
            print("🔵 [FreeRecordingNew] showNoteSheet: \(showNoteSheet)")
            print("🔵 [FreeRecordingNew] showSaveButton: \(showSaveButton)")
            print("🔵 [FreeRecordingNew] isRecording: \(isRecording)")
        }
        .sheet(isPresented: $showNoteSheet) {
            noteInputSheet
        }
        .overlay {
            if isUploading {
                uploadingOverlay
            }
        }
        .alert("上传失败", isPresented: .constant(uploadError != nil)) {
            Button("确定") {
                uploadError = nil
                dismiss()
            }
        } message: {
            Text(uploadError ?? "")
        }
        .alert("上传成功", isPresented: $uploadSuccess) {
            Button("确定") {
                uploadSuccess = false
                dismiss()
            }
        } message: {
            Text("数据已成功保存到服务器")
        }
    }
    
    // MARK: - UI Components
    
    private var backgroundGradient: some View {
        LinearGradient(
            colors: [.black.opacity(0.95), .purple.opacity(0.5), .pink.opacity(0.3)],
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
        .ignoresSafeArea()
    }
    
    private var headerSection: some View {
        VStack(spacing: 8) {
            Image(systemName: "record.circle.fill")
                .font(.system(size: 50, weight: .bold))
                .foregroundStyle(LinearGradient(
                    colors: [.purple, .pink, .orange],
                    startPoint: .topLeading,
                    endPoint: .bottomTrailing
                ))
            
            Text("自由记录")
                .font(.system(.title, design: .rounded).weight(.bold))
                .foregroundColor(.white)
            
            Text("记录完整用餐过程")
                .font(.system(.subheadline, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
        }
        .padding(.top, 40)
    }
    
    private var statusSection: some View {
        VStack(spacing: 20) {
            // 时长显示
            VStack(spacing: 8) {
                Text("总时长")
                    .font(.system(.caption, design: .rounded))
                    .foregroundColor(.white.opacity(0.7))
                Text(formatTime(elapsedTime))
                    .font(.system(size: 48, weight: .bold, design: .rounded))
                    .foregroundColor(.white)
            }
            
            // 当前状态
            statusIndicator
            
            // 实时传感器数据
            if isRecording {
                sensorDataDisplay
            }
            
            // 统计信息
            statisticsCards
        }
    }
    
    private var statusIndicator: some View {
        HStack(spacing: 12) {
            Circle()
                .fill(isRecording ? (isChewing ? Color.green : Color.orange) : Color.gray)
                .frame(width: 12, height: 12)
            
            Text(isRecording ? (isChewing ? "咀嚼中" : "非咀嚼中") : "未开始")
                .font(.system(.headline, design: .rounded))
                .foregroundColor(.white)
        }
        .padding(.horizontal, 20)
        .padding(.vertical, 10)
        .background(.white.opacity(0.1))
        .cornerRadius(20)
    }
    
    private var sensorDataDisplay: some View {
        VStack(spacing: 12) {
            // 加速度计
            SensorRow(
                title: "加速度计",
                icon: "arrow.up.and.down.and.arrow.left.and.right",
                color: .cyan,
                x: sensor.currentAccX,
                y: sensor.currentAccY,
                z: sensor.currentAccZ
            )
            
            // 陀螺仪
            SensorRow(
                title: "陀螺仪",
                icon: "gyroscope",
                color: .orange,
                x: sensor.currentGyroX,
                y: sensor.currentGyroY,
                z: sensor.currentGyroZ
            )
        }
    }
    
    private var statisticsCards: some View {
        HStack(spacing: 30) {
            StatCard(title: "咀嚼段", value: "\(session.chewingSegments.count)", color: .green)
            StatCard(title: "非咀嚼段", value: "\(session.nonChewingSegments.count)", color: .orange)
            StatCard(title: "样本数", value: "\(sensor.sampleCount)", color: .cyan)
        }
    }
    
    private var controlButtons: some View {
        VStack(spacing: 16) {
            if !isRecording && !showSaveButton {
                // 开始按钮
                startButton
                cancelButton
            } else if showSaveButton {
                // 保存按钮
                saveButton
            } else {
                // 录制中的按钮
                toggleButton
                finishButton
            }
        }
        .padding(.horizontal, 30)
        .padding(.bottom, 40)
    }
    
    private var startButton: some View {
        Button(action: startRecording) {
            Label("开始咀嚼", systemImage: "play.fill")
                .font(.system(.title3, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 18)
                .background(LinearGradient(
                    colors: [.green, .teal],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .cornerRadius(16)
        }
    }
    
    private var toggleButton: some View {
        Button(action: toggleChewing) {
            Label(isChewing ? "停止咀嚼" : "继续咀嚼", systemImage: isChewing ? "pause.fill" : "play.fill")
                .font(.system(.title3, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 18)
                .background(LinearGradient(
                    colors: isChewing ? [.orange, .red] : [.green, .teal],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .cornerRadius(16)
        }
    }
    
    private var finishButton: some View {
        Button(action: finishRecording) {
            Label("结束记录", systemImage: "stop.fill")
                .font(.system(.headline, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 16)
                .background(.red.opacity(0.8))
                .cornerRadius(16)
        }
    }
    
    private var saveButton: some View {
        Button(action: { showNoteSheet = true }) {
            Label("保存记录", systemImage: "square.and.arrow.down.fill")
                .font(.system(.title3, design: .rounded).weight(.semibold))
                .foregroundColor(.white)
                .frame(maxWidth: .infinity)
                .padding(.vertical, 18)
                .background(LinearGradient(
                    colors: [.blue, .purple],
                    startPoint: .leading,
                    endPoint: .trailing
                ))
                .cornerRadius(16)
        }
    }
    
    private var cancelButton: some View {
        Button("取消") {
            dismiss()
        }
        .font(.system(.body, design: .rounded))
        .foregroundColor(.white.opacity(0.7))
    }
    
    private var noteInputSheet: some View {
        VStack(spacing: 16) {
            Capsule()
                .fill(.secondary.opacity(0.4))
                .frame(width: 40, height: 5)
                .padding(.top, 8)
                .onAppear {
                    print("🟡 [FreeRecordingNew] 备注弹窗出现")
                }
            
            Text("记录备注")
                .font(.headline)
            
            Text("请输入吃的东西（必填）")
                .font(.footnote)
                .foregroundColor(.secondary)
            
            TextField("如：花生/苹果", text: $noteText)
                .textFieldStyle(.roundedBorder)
            
            HStack(spacing: 12) {
                Button("稍后填写") {
                    showNoteSheet = false
                }
                .buttonStyle(.bordered)
                
                Button("保存") {
                    saveAndUpload()
                }
                .buttonStyle(.borderedProminent)
                .disabled(noteText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty)
            }
            
            Spacer(minLength: 0)
        }
        .padding(20)
    }
    
    private var uploadingOverlay: some View {
        ZStack {
            Color.black.opacity(0.5).ignoresSafeArea()
            VStack(spacing: 20) {
                ProgressView()
                    .scaleEffect(1.5)
                    .tint(.white)
                Text("正在上传数据...")
                    .font(.system(.body, design: .rounded).weight(.medium))
                    .foregroundColor(.white)
            }
            .padding(40)
            .background(.ultraThinMaterial, in: RoundedRectangle(cornerRadius: 20))
        }
    }
    
    // MARK: - Recording Logic
    
    private func startRecording() {
        print("▶️ [FreeRecording] 开始录制")
        
        isRecording = true
        isChewing = true
        session = FreeRecordingSession()
        currentSegmentStartDate = Date()
        currentSegmentStartIndex = 0
        
        // 启动传感器
        sensor.start(rateHz: 50)
        
        // 启动计时器
        elapsedTime = 0
        timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { _ in
            elapsedTime = Date().timeIntervalSince(session.startDate)
        }
    }
    
    private func toggleChewing() {
        print("🔄 [FreeRecording] 切换状态: \(isChewing ? "咀嚼" : "非咀嚼") -> \(isChewing ? "非咀嚼" : "咀嚼")")
        
        // 保存当前段
        saveCurrentSegment()
        
        // 切换状态
        isChewing.toggle()
        
        // 开始新段
        currentSegmentStartDate = Date()
        currentSegmentStartIndex = sensor.rawSamples.count
    }
    
    private func finishRecording() {
        print("⏹️ [FreeRecording] 结束录制，样本数: \(sensor.sampleCount)")
        
        // 保存最后一段
        saveCurrentSegment()
        
        // 停止传感器和计时器
        sensor.stop()
        timer?.invalidate()
        timer = nil
        
        isRecording = false
        session.endDate = Date()
        
        // 只有有数据才显示保存按钮
        if sensor.sampleCount > 0 {
            showSaveButton = true
        } else {
            print("⚠️ [FreeRecording] 无数据，返回")
            dismiss()
        }
    }
    
    private func saveCurrentSegment() {
        guard let startDate = currentSegmentStartDate else { return }
        
        let endDate = Date()
        let endIndex = sensor.rawSamples.count
        
        guard endIndex > currentSegmentStartIndex else {
            print("⚠️ [FreeRecording] 段数据为空，跳过")
            return
        }
        
        let rawSamples = Array(sensor.rawSamples[currentSegmentStartIndex..<endIndex])
        let linSamples = Array(sensor.linSamples[currentSegmentStartIndex..<endIndex])
        
        let segment = RecordingSegment(
            type: isChewing ? .chewing : .nonChewing,
            startDate: startDate,
            endDate: endDate,
            rawSamples: rawSamples,
            linSamples: linSamples
        )
        
        session.segments.append(segment)
        print("✅ [FreeRecording] 保存段: \(segment.type.rawValue), 样本数: \(rawSamples.count)")
    }
    
    private func saveAndUpload() {
        showNoteSheet = false
        session.note = noteText
        
        Task {
            await uploadDataToServer()
        }
    }
    
    // MARK: - Upload
    
    private func uploadDataToServer() async {
        await MainActor.run { isUploading = true }
        
        do {
            let timestamp = Int(Date().timeIntervalSince1970)
            
            // 上传每个段
            for (index, segment) in session.segments.enumerated() {
                let segmentTimestamp = Int(segment.startDate.timeIntervalSince1970)
                
                // 创建 CSV 文件
                let rawURL = try createCSV(samples: segment.rawSamples, type: "raw", suffix: "\(segment.type.rawValue)_\(index)")
                let linURL = try createCSV(samples: segment.linSamples, type: "lin", suffix: "\(segment.type.rawValue)_\(index)")
                
                // 上传到 OSS
                let rawKey = "chew_data/\(userName)/\(segmentTimestamp)_\(segment.type.rawValue)_\(index)_raw.csv"
                let linKey = "chew_data/\(userName)/\(segmentTimestamp)_\(segment.type.rawValue)_\(index)_lin.csv"
                
                let rawOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: rawURL, objectKey: rawKey)
                let linOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: linURL, objectKey: linKey)
                
                // 调用后端接口
                try await ChewDataService.shared.saveChewData(
                    scenario: "自由记录-\(segment.type.rawValue)",
                    note: noteText,
                    userName: userName,
                    duration: segment.duration,
                    rawCsvUrl: rawOSSUrl,
                    linCsvUrl: linOSSUrl,
                    timestamp: segment.startDate,
                    sessionUUID: session.sessionUUID
                )
            }
            
            // 上传完整文件
            let completeRawURL = try createCSV(samples: sensor.rawSamples, type: "raw", suffix: "complete")
            let completeLinURL = try createCSV(samples: sensor.linSamples, type: "lin", suffix: "complete")
            
            let completeRawKey = "chew_data/\(userName)/\(timestamp)_complete_raw.csv"
            let completeLinKey = "chew_data/\(userName)/\(timestamp)_complete_lin.csv"
            
            let completeRawOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: completeRawURL, objectKey: completeRawKey)
            let completeLinOSSUrl = try await OSSUploadService.shared.uploadFile(fileURL: completeLinURL, objectKey: completeLinKey)
            
            try await ChewDataService.shared.saveChewData(
                scenario: "自由记录-complete",
                note: noteText,
                userName: userName,
                duration: session.totalDuration,
                rawCsvUrl: completeRawOSSUrl,
                linCsvUrl: completeLinOSSUrl,
                timestamp: session.startDate,
                sessionUUID: session.sessionUUID
            )
            
            await MainActor.run {
                isUploading = false
                uploadSuccess = true
            }
            
        } catch {
            await MainActor.run {
                isUploading = false
                uploadError = error.localizedDescription
            }
        }
    }
    
    private func createCSV(samples: [Any], type: String, suffix: String) throws -> URL {
        let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let fileName = "\(userName)_\(suffix)_\(type).csv"
        let fileURL = dir.appendingPathComponent(fileName)
        
        let csvContent: String
        if type == "raw", let rawSamples = samples as? [RawSample] {
            csvContent = buildRawCSV(rawSamples)
        } else if type == "lin", let linSamples = samples as? [LinSample] {
            csvContent = buildLinCSV(linSamples)
        } else {
            throw NSError(domain: "", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid sample type"])
        }
        
        try csvContent.data(using: .utf8)?.write(to: fileURL, options: .atomic)
        return fileURL
    }
    
    private func buildRawCSV(_ samples: [RawSample]) -> String {
        var s = "timestamp,ax,ay,az,wx,wy,wz\n"
        for r in samples {
            s += String(format: "%.6f,%.6f,%.6f,%.6f,%.6f,%.6f,%.6f\n", r.t, r.ax, r.ay, r.az, r.wx, r.wy, r.wz)
        }
        return s
    }
    
    private func buildLinCSV(_ samples: [LinSample]) -> String {
        var s = "timestamp,ax_lin,ay_lin,az_lin\n"
        for v in samples {
            s += String(format: "%.6f,%.6f,%.6f,%.6f\n", v.t, v.ax_lin, v.ay_lin, v.az_lin)
        }
        return s
    }
    
    private func formatTime(_ time: TimeInterval) -> String {
        let minutes = Int(time) / 60
        let seconds = Int(time) % 60
        return String(format: "%02d:%02d", minutes, seconds)
    }
}

// MARK: - Supporting Views

private struct SensorRow: View {
    let title: String
    let icon: String
    let color: Color
    let x: Double
    let y: Double
    let z: Double
    
    var body: some View {
        VStack(spacing: 8) {
            HStack(spacing: 8) {
                Image(systemName: icon)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(color)
                Text(title)
                    .font(.system(.caption, design: .rounded).weight(.semibold))
                    .foregroundColor(.white)
                Spacer()
            }
            
            HStack(spacing: 12) {
                AxisLabel(label: "X", value: x, color: .red)
                AxisLabel(label: "Y", value: y, color: .green)
                AxisLabel(label: "Z", value: z, color: .blue)
            }
        }
        .padding(12)
        .background(.white.opacity(0.1))
        .cornerRadius(12)
    }
}

private struct AxisLabel: View {
    let label: String
    let value: Double
    let color: Color
    
    var body: some View {
        VStack(spacing: 4) {
            Text(label)
                .font(.system(.caption2, design: .rounded).weight(.bold))
                .foregroundColor(color)
            Text(String(format: "%.3f", value))
                .font(.system(.caption, design: .monospaced).weight(.medium))
                .foregroundColor(.white)
        }
        .frame(maxWidth: .infinity)
    }
}

private struct StatCard: View {
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(spacing: 6) {
            Text(value)
                .font(.system(.title2, design: .rounded).weight(.bold))
                .foregroundColor(color)
            Text(title)
                .font(.system(.caption2, design: .rounded))
                .foregroundColor(.white.opacity(0.7))
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, 12)
        .background(.white.opacity(0.1))
        .cornerRadius(12)
    }
}
